package com.cskaoyan.service.mallservice;

import com.cskaoyan.bean.mallbean.Storage;
import com.cskaoyan.config.AliyunCompoent;
import com.cskaoyan.mapper.mallmapper.StorageMapper;
import com.cskaoyan.vo.mallvo.StorageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author hsp
 * @date 2021/5/11 0:19
 */
@Service
public class ImageServiceImpOss implements ImageService {

    @Autowired
    AliyunCompoent aliyunCompoent;
    @Autowired
    StorageMapper storageMapper;
    @Override
    public StorageVo createStorage(MultipartFile file) {
        InputStream inputStream = null;
        try {
             inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String originalFilename = file.getOriginalFilename();
        int indexDot = originalFilename.indexOf(".");
        //获得.jpg .png .gif等
        String fileSuffix = originalFilename.substring(indexDot);
//       String newFileName = UUID.randomUUID().toString().replaceAll("-","").substring(0,20)+ fileSuffix;
       InputStream inputStream2 = null;
        try {
            inputStream2 =  file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String newFileName = null;
        try {
            newFileName = DigestUtils.md5DigestAsHex(inputStream2).substring(0,20) + fileSuffix;
        } catch (IOException e) {
            e.printStackTrace();
        }
        aliyunCompoent.FileUpload(newFileName,inputStream);


        Storage storage = new Storage();
        storage.setId(null);
        storage.setKey(newFileName);
        storage.setName(file.getOriginalFilename());
        storage.setType(file.getContentType());
        storage.setSize((int) file.getSize());
        storage.setUrl("https://"+aliyunCompoent.getOss().getBucket()+"."+aliyunCompoent.getOss().getEndPoint()+"/"+newFileName);
        // todo addTime应是不变的
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        storage.setDeleted(false);

        storageMapper.insert(storage);


        StorageVo storageVo = new StorageVo();

        storageVo.setAddTime(new SimpleDateFormat().format(storage.getAddTime()));
        storageVo.setId(storage.getId());
        storageVo.setKey(storage.getKey());
        storageVo.setName(storage.getName());
        storageVo.setSize(storage.getSize());
        storageVo.setType(storage.getType());
        storageVo.setUpdateTime(new SimpleDateFormat().format(storage.getUpdateTime()));
        storageVo.setUrl(storage.getUrl());
        return storageVo;
    }
}
